package org.dragonnova.business.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.UUID;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;

import org.dragonnova.business.model.TagValue;
import org.dragonnova.business.model.WxConfig;
import org.dragonnova.business.model.WxDataValueColor;
import org.dragonnova.business.model.WxTemplate;
import org.dragonnova.business.model.WxTemplateData;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.base.pub.util.StringUtils;

public class WeixinUtil {

	/**
	 * 方法名：httpRequest</br>
	 * 详述：发送http请求</br>
	 * 创建时间：2016-1-5 </br>
	 * 
	 * @param requestUrl
	 * @param requestMethod
	 * @param outputStr
	 * @return 说明返回值含义
	 * @throws 说明发生此异常的条件
	 */
	public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
		String resultStr = null;
		StringBuffer buffer = new StringBuffer();
		try {
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			httpUrlConn.setRequestMethod(requestMethod);
			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			resultStr = buffer.toString();
		} catch (ConnectException ce) {
			ce.printStackTrace();
			return "{\"error\":\""+ce.getMessage()+"\"}";
		} catch (Exception e) {
			e.printStackTrace();
			return "{\"error\":\""+e.getMessage()+"\"}";
		}
		return resultStr;
	}

	/**
	 * 方法名：getWxConfig</br>
	 * 详述：获取微信的配置信息 </br>
	 * 开发人员：souvc </br>
	 * 创建时间：2016-1-5 </br>
	 * 
	 * @param request
	 * @return 说明返回值含义
	 * @throws 说明发生此异常的条件
	 */
	public static WxConfig getWxConfig(HttpServletRequest request, WxConfig wxc) {
		String appId = wxc.getAppid();// "wx3790efddfc4e38b4"; // 必填，公众号的唯一标识
		String secret = wxc.getSecret();// "a75de74b6708c4dbdf1e265a5cdf6291";
		String requestUrl = wxc.getRequestUrl();// request.getRequestURI();//
		String access_token = getAccessToken(appId, secret);
		String jsapi_ticket = "";
		int timestamp = (int) (System.currentTimeMillis() / 1000); // 必填，生成签名的时间戳
		String nonceStr = UUID.randomUUID().toString(); // 必填，生成签名的随机串
		if (access_token != null && !"".equals(access_token)) {
			jsapi_ticket = getJsapiTicket(access_token);
		}
		String signature = "";
		String sign = StringUtils.concat("jsapi_ticket=", jsapi_ticket, "&noncestr=", nonceStr, "&timestamp=",
				String.valueOf(timestamp), "&url=", requestUrl);
		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(sign.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		wxc.setAppid(appId);
		wxc.setTimestamp(timestamp);
		wxc.setNonceStr(nonceStr);
		wxc.setSignature(signature);
		wxc.setRequestUrl(requestUrl);
		wxc.setJsapi_ticket(jsapi_ticket);
		wxc.setAccess_token(access_token);
		return wxc;
	}

	/**
	 * 方法名：byteToHex</br>
	 * 详述：字符串加密辅助方法 </br>
	 * 开发人员：souvc </br>
	 * 创建时间：2016-1-5 </br>
	 * 
	 * @param hash
	 * @return 说明返回值含义
	 * @throws 说明发生此异常的条件
	 */
	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}

	/**
	 * // 获取access_token
	 * 
	 * @return
	 */
	public static String getAccessToken(String appId, String secret) {
		String url = StringUtils.concat("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=",
				appId, "&secret=", secret);
		JSONObject json = JSON.parseObject(WeixinUtil.httpRequest(url, "GET", null));
		return json != null ? json.getString("access_token") : "";
	}

	/**
	 * // 获取JsapiTicket
	 * 
	 * @return
	 */
	public static String getJsapiTicket(String accessToken) {
		String url = StringUtils.concat("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=", accessToken,
				"&type=jsapi");
		JSONObject json = JSON.parseObject(WeixinUtil.httpRequest(url, "GET", null));
		return json != null ? json.getString("ticket") : "";
	}
	/**
	 * //获取模版id
	 * 
	 * @return
	 */
	public static String getTemplateId(String accessToken) {
		String url = StringUtils.concat("https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=", accessToken,
				"&type=jsapi");
		JSONObject json = JSON.parseObject(WeixinUtil.httpRequest(url, "GET", null));
		System.out.println("get templateId result :"+json.toString());
		return json != null ? json.getString("industry_id1") : "";
	}

	/**
	 * 发送微信模版消息
	 * 
	 * @param openid微信用户的openid
	 */
	public static void sendTemplate(String openid, String accessToken, String templateId, TagValue tagvalue) {
		String url = StringUtils.concat("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=",
				accessToken);
		WxTemplate wxTemplate = new WxTemplate();
		WxTemplateData data = new WxTemplateData();
		data.setFirst(new WxDataValueColor("警告，数据异常！", "#173177"));
		data.setKeynote1(new WxDataValueColor("路由器1", "#173177"));
		data.setKeynote2(new WxDataValueColor("湿度：79%，温度：88°C", "#ff3177"));
		data.setKeynote3(new WxDataValueColor("2017年4月13日 19:37", "#173177"));
		data.setRemark(new WxDataValueColor("请尽快处理！", "#000080"));
		wxTemplate.setTouser(openid);
		wxTemplate.setData(data);
		wxTemplate.setUrl(url);
		wxTemplate.setTemplate_id(templateId);
		String json = JSONObject.toJSONString(wxTemplate);
		System.out.println("send wx Template result : "+WeixinUtil.httpRequest(url, "GET", json));
	}

	public static void main(String[] args) {
		String accessToken = getAccessToken("wx3790efddfc4e38b4", "a75de74b6708c4dbdf1e265a5cdf6291");
		String templateId = getTemplateId(accessToken);
//		System.out.println(accessToken);
		sendTemplate("asdsfwe123124", accessToken, templateId, null);
	}
}
